Hi, can anyone help with this error "heap corruption detected" ?
Here is my program:
Code:#include "stdafx.h" #include "iostream" #include "cassert" using namespace std; int capacity = 4; // default capacity double* billsAndCoins = new double[capacity]; // data storage for change int nBillsAndCoins = -1; // track the number of coins and bills // -1 means invalid, 0 means no change due, >0 is #of bills+coins changed bool set(double, double); // first parameter is price, last is amount paid double calc(double, double); // first parameter is denomination, last is change bool isValid(); // return false if the number of coins+bills int i; // iteration tracker void myIterator(); // set index of array to 0 bool hasNext(); // return the index number of coins+bills in the array double next(); // return a value from the array and advanced the index void release(); // delete the dynamic allocated array int main() { set (14.57, 50); if (!isValid()) // function checks if #of bills+coins is 0 or greater cout << "Invalid input\n"; else { // print the change for (myIterator(); hasNext();) cout << '[' << next() << ']'; } cout << endl; set (63.68, 80); if (!isValid()) // function checks if #of bills+coins is 0 or greater cout << "Invalid input\n"; else { // print the change for (myIterator(); hasNext();) cout << '[' << next() << ']'; } cout << endl; release(); // contains the statement that deletes the dynamic array cin.get(); return 0; } bool set(double price, double paid) { double change = paid - price; if(change == 0) { nBillsAndCoins = 0; cout << "No Change"; return true; } else if(change > 0) { nBillsAndCoins = 0; double money[11] = {100,50,20,10,5,1,0.5,0.25,0.1,0.05,0.01}; //denomination storage for(int j = 0; j < 11; j++) change = calc(money[j], change); // if the change is still not 0 due to some errors (the change become very small), it rounds off to 0 if(change < 0.00001) change = 0; // if the change is still not 0 due to representational error, automatically allocate 1 penny to the array if(change >= 0.009) { change = 0; billsAndCoins[nBillsAndCoins] = 0.01; nBillsAndCoins++; } assert(change == 0); return true; } else return false; } double calc(double Money, double Change) { while(Change >= Money) { // check and doubling the size y for overloading arrays if (nBillsAndCoins == capacity) { capacity *= 2; double* temp = new double[capacity]; for (int i = 0; i < nBillsAndCoins; i++) temp[i] = billsAndCoins[i]; delete [] billsAndCoins; billsAndCoins = temp; } Change -= Money; billsAndCoins[nBillsAndCoins] = Money; nBillsAndCoins++; // but if I add " cout << Change << cin.get(); " the program has no error } return Change; } bool isValid() { if(nBillsAndCoins < 0) return false; else return true; } void myIterator() { i=0; } bool hasNext() { return i >= 0 && i < nBillsAndCoins; } double next() { return billsAndCoins[i++]; } void release() { delete [] billsAndCoins; }

